import React, { useState, useEffect } from 'react';
import {
  Card,
  Form,
  Switch,
  Select,
  Button,
  message,
  Tabs,
  Divider,
  Space,
  Row,
  Col,
  InputNumber,
  Radio,
  Alert,
  Modal,
  List,
  Typography,
} from 'antd';
import {
  SettingOutlined,
  NotificationOutlined,
  SecurityScanOutlined,
  DatabaseOutlined,
  ExportOutlined,
  ImportOutlined,
  DeleteOutlined,
  ExclamationCircleOutlined,
} from '@ant-design/icons';
import { useAppDispatch, useAppSelector } from '../store/hooks';
import { setTheme } from '../store/slices/uiSlice';

// const { TabPane } = Tabs; // Deprecated, using items instead
const { Option } = Select;
const { Text } = Typography;
const { confirm } = Modal;

interface SystemSettings {
  theme: 'light' | 'dark';
  language: 'zh-CN' | 'en-US';
  timezone: string;
  dateFormat: string;
  currency: string;
}

interface NotificationSettings {
  emailNotifications: boolean;
  smsNotifications: boolean;
  pushNotifications: boolean;
  portfolioAlerts: boolean;
  priceAlerts: boolean;
  newsAlerts: boolean;
  systemAlerts: boolean;
}

interface TradingSettings {
  autoRebalance: boolean;
  rebalanceThreshold: number;
  stopLossEnabled: boolean;
  defaultStopLoss: number;
  riskWarningEnabled: boolean;
  confirmTransactions: boolean;
}

const Settings: React.FC = () => {
  const dispatch = useAppDispatch();
  const { theme, notifications } = useAppSelector((state: any) => state.ui);
  const [systemForm] = Form.useForm();
  const [notificationForm] = Form.useForm();
  const [tradingForm] = Form.useForm();
  const [loading, setLoading] = useState(false);

  const [systemSettings, setSystemSettings] = useState<SystemSettings>({
    theme: 'light',
    language: 'zh-CN',
    timezone: 'Asia/Shanghai',
    dateFormat: 'YYYY-MM-DD',
    currency: 'CNY',
  });

  const [notificationSettings, setNotificationSettings] = useState<NotificationSettings>({
    emailNotifications: true,
    smsNotifications: false,
    pushNotifications: true,
    portfolioAlerts: true,
    priceAlerts: true,
    newsAlerts: false,
    systemAlerts: true,
  });

  const [tradingSettings, setTradingSettings] = useState<TradingSettings>({
    autoRebalance: false,
    rebalanceThreshold: 5,
    stopLossEnabled: true,
    defaultStopLoss: 10,
    riskWarningEnabled: true,
    confirmTransactions: true,
  });

  useEffect(() => {
    // 从localStorage加载设置
    const savedSystemSettings = localStorage.getItem('systemSettings');
    const savedNotificationSettings = localStorage.getItem('notificationSettings');
    const savedTradingSettings = localStorage.getItem('tradingSettings');

    if (savedSystemSettings) {
      const settings = JSON.parse(savedSystemSettings);
      setSystemSettings(settings);
      systemForm.setFieldsValue(settings);
    }

    if (savedNotificationSettings) {
      const settings = JSON.parse(savedNotificationSettings);
      setNotificationSettings(settings);
      notificationForm.setFieldsValue(settings);
    }

    if (savedTradingSettings) {
      const settings = JSON.parse(savedTradingSettings);
      setTradingSettings(settings);
      tradingForm.setFieldsValue(settings);
    }
  }, [systemForm, notificationForm, tradingForm]);

  const handleSystemSettingsUpdate = async (values: SystemSettings) => {
    setLoading(true);
    try {
      setSystemSettings(values);
      localStorage.setItem('systemSettings', JSON.stringify(values));
      
      // 更新Redux状态
      if (values.theme !== theme) {
        dispatch(setTheme(values.theme));
      }
      
      message.success('系统设置已保存');
    } catch (error) {
      message.error('保存设置失败');
    } finally {
      setLoading(false);
    }
  };

  const handleNotificationSettingsUpdate = async (values: NotificationSettings) => {
    setLoading(true);
    try {
      setNotificationSettings(values);
      localStorage.setItem('notificationSettings', JSON.stringify(values));
      
      // 通知设置已保存到localStorage
      
      message.success('通知设置已保存');
    } catch (error) {
      message.error('保存设置失败');
    } finally {
      setLoading(false);
    }
  };

  const handleTradingSettingsUpdate = async (values: TradingSettings) => {
    setLoading(true);
    try {
      setTradingSettings(values);
      localStorage.setItem('tradingSettings', JSON.stringify(values));
      message.success('交易设置已保存');
    } catch (error) {
      message.error('保存设置失败');
    } finally {
      setLoading(false);
    }
  };

  const handleExportData = () => {
    confirm({
      title: '导出数据',
      icon: <ExclamationCircleOutlined />,
      content: '确定要导出所有数据吗？这可能需要一些时间。',
      onOk() {
        message.info('数据导出功能开发中...');
      },
    });
  };

  const handleImportData = () => {
    confirm({
      title: '导入数据',
      icon: <ExclamationCircleOutlined />,
      content: '导入数据将覆盖现有数据，确定要继续吗？',
      onOk() {
        message.info('数据导入功能开发中...');
      },
    });
  };

  const handleClearCache = () => {
    confirm({
      title: '清除缓存',
      icon: <ExclamationCircleOutlined />,
      content: '确定要清除所有缓存数据吗？这将提高系统性能但可能需要重新加载数据。',
      onOk() {
        // 清除除了认证信息外的所有localStorage数据
        const token = localStorage.getItem('token');
        const user = localStorage.getItem('user');
        localStorage.clear();
        if (token) localStorage.setItem('token', token);
        if (user) localStorage.setItem('user', user);
        message.success('缓存已清除');
      },
    });
  };

  const handleResetSettings = () => {
    confirm({
      title: '重置设置',
      icon: <ExclamationCircleOutlined />,
      content: '确定要重置所有设置到默认值吗？此操作不可撤销。',
      onOk() {
        // 重置所有设置
        const defaultSystemSettings = {
          theme: 'light' as const,
          language: 'zh-CN' as const,
          timezone: 'Asia/Shanghai',
          dateFormat: 'YYYY-MM-DD',
          currency: 'CNY',
        };
        
        const defaultNotificationSettings = {
          emailNotifications: true,
          smsNotifications: false,
          pushNotifications: true,
          portfolioAlerts: true,
          priceAlerts: true,
          newsAlerts: false,
          systemAlerts: true,
        };
        
        const defaultTradingSettings = {
          autoRebalance: false,
          rebalanceThreshold: 5,
          stopLossEnabled: true,
          defaultStopLoss: 10,
          riskWarningEnabled: true,
          confirmTransactions: true,
        };
        
        setSystemSettings(defaultSystemSettings);
        setNotificationSettings(defaultNotificationSettings);
        setTradingSettings(defaultTradingSettings);
        
        systemForm.setFieldsValue(defaultSystemSettings);
        notificationForm.setFieldsValue(defaultNotificationSettings);
        tradingForm.setFieldsValue(defaultTradingSettings);
        
        localStorage.removeItem('systemSettings');
        localStorage.removeItem('notificationSettings');
        localStorage.removeItem('tradingSettings');
        
        message.success('设置已重置');
      },
    });
  };

  return (
    <div style={{ padding: '24px' }}>
      <Card>
        <Tabs 
          defaultActiveKey="system"
          items={[
            {
              key: 'system',
              label: <span><SettingOutlined />系统设置</span>,
              children: (
            <Form
              form={systemForm}
              layout="vertical"
              onFinish={handleSystemSettingsUpdate}
              initialValues={systemSettings}
            >
              <Row gutter={[24, 16]}>
                <Col xs={24} md={12}>
                  <Form.Item label="主题" name="theme">
                    <Radio.Group>
                      <Radio.Button value="light">浅色</Radio.Button>
                      <Radio.Button value="dark">深色</Radio.Button>
                    </Radio.Group>
                  </Form.Item>
                </Col>
                <Col xs={24} md={12}>
                  <Form.Item label="语言" name="language">
                    <Select>
                      <Option value="zh-CN">简体中文</Option>
                      <Option value="en-US">English</Option>
                    </Select>
                  </Form.Item>
                </Col>
              </Row>
              
              <Row gutter={[24, 16]}>
                <Col xs={24} md={12}>
                  <Form.Item label="时区" name="timezone">
                    <Select>
                      <Option value="Asia/Shanghai">北京时间 (UTC+8)</Option>
                      <Option value="America/New_York">纽约时间 (UTC-5)</Option>
                      <Option value="Europe/London">伦敦时间 (UTC+0)</Option>
                      <Option value="Asia/Tokyo">东京时间 (UTC+9)</Option>
                    </Select>
                  </Form.Item>
                </Col>
                <Col xs={24} md={12}>
                  <Form.Item label="日期格式" name="dateFormat">
                    <Select>
                      <Option value="YYYY-MM-DD">2024-01-01</Option>
                      <Option value="DD/MM/YYYY">01/01/2024</Option>
                      <Option value="MM/DD/YYYY">01/01/2024</Option>
                      <Option value="YYYY年MM月DD日">2024年01月01日</Option>
                    </Select>
                  </Form.Item>
                </Col>
              </Row>
              
              <Row gutter={[24, 16]}>
                <Col xs={24} md={12}>
                  <Form.Item label="货币单位" name="currency">
                    <Select>
                      <Option value="CNY">人民币 (¥)</Option>
                      <Option value="USD">美元 ($)</Option>
                      <Option value="EUR">欧元 (€)</Option>
                      <Option value="JPY">日元 (¥)</Option>
                    </Select>
                  </Form.Item>
                </Col>
              </Row>
              
              <Form.Item>
                <Button type="primary" htmlType="submit" loading={loading}>
                  保存系统设置
                </Button>
              </Form.Item>
            </Form>
              )
            },
            {
              key: 'notifications',
              label: <span><NotificationOutlined />通知设置</span>,
              children: (
            <Form
              form={notificationForm}
              layout="vertical"
              onFinish={handleNotificationSettingsUpdate}
              initialValues={notificationSettings}
            >
              <Alert
                message="通知设置"
                description="配置您希望接收的通知类型和方式"
                type="info"
                showIcon
                style={{ marginBottom: '24px' }}
              />
              
              <Card title="通知方式" size="small" style={{ marginBottom: '16px' }}>
                <Row gutter={[24, 16]}>
                  <Col xs={24} md={8}>
                    <Form.Item name="emailNotifications" valuePropName="checked">
                      <Space>
                        <Switch />
                        <Text>邮件通知</Text>
                      </Space>
                    </Form.Item>
                  </Col>
                  <Col xs={24} md={8}>
                    <Form.Item name="smsNotifications" valuePropName="checked">
                      <Space>
                        <Switch />
                        <Text>短信通知</Text>
                      </Space>
                    </Form.Item>
                  </Col>
                  <Col xs={24} md={8}>
                    <Form.Item name="pushNotifications" valuePropName="checked">
                      <Space>
                        <Switch />
                        <Text>推送通知</Text>
                      </Space>
                    </Form.Item>
                  </Col>
                </Row>
              </Card>
              
              <Card title="通知内容" size="small">
                <Row gutter={[24, 16]}>
                  <Col xs={24} md={12}>
                    <Form.Item name="portfolioAlerts" valuePropName="checked">
                      <Space>
                        <Switch />
                        <Text>投资组合提醒</Text>
                      </Space>
                    </Form.Item>
                  </Col>
                  <Col xs={24} md={12}>
                    <Form.Item name="priceAlerts" valuePropName="checked">
                      <Space>
                        <Switch />
                        <Text>价格提醒</Text>
                      </Space>
                    </Form.Item>
                  </Col>
                  <Col xs={24} md={12}>
                    <Form.Item name="newsAlerts" valuePropName="checked">
                      <Space>
                        <Switch />
                        <Text>新闻提醒</Text>
                      </Space>
                    </Form.Item>
                  </Col>
                  <Col xs={24} md={12}>
                    <Form.Item name="systemAlerts" valuePropName="checked">
                      <Space>
                        <Switch />
                        <Text>系统提醒</Text>
                      </Space>
                    </Form.Item>
                  </Col>
                </Row>
              </Card>
              
              <Form.Item style={{ marginTop: '24px' }}>
                <Button type="primary" htmlType="submit" loading={loading}>
                  保存通知设置
                </Button>
              </Form.Item>
            </Form>
              )
            },
            {
              key: 'trading',
              label: <span><SecurityScanOutlined />交易设置</span>,
              children: (
            <Form
              form={tradingForm}
              layout="vertical"
              onFinish={handleTradingSettingsUpdate}
              initialValues={tradingSettings}
            >
              <Alert
                message="交易设置"
                description="配置自动交易和风险控制参数"
                type="warning"
                showIcon
                style={{ marginBottom: '24px' }}
              />
              
              <Card title="自动交易" size="small" style={{ marginBottom: '16px' }}>
                <Row gutter={[24, 16]}>
                  <Col xs={24} md={12}>
                    <Form.Item name="autoRebalance" valuePropName="checked">
                      <Space>
                        <Switch />
                        <Text>自动再平衡</Text>
                      </Space>
                    </Form.Item>
                  </Col>
                  <Col xs={24} md={12}>
                    <Form.Item label="再平衡阈值 (%)" name="rebalanceThreshold">
                      <InputNumber min={1} max={20} style={{ width: '100%' }} />
                    </Form.Item>
                  </Col>
                </Row>
              </Card>
              
              <Card title="风险控制" size="small" style={{ marginBottom: '16px' }}>
                <Row gutter={[24, 16]}>
                  <Col xs={24} md={12}>
                    <Form.Item name="stopLossEnabled" valuePropName="checked">
                      <Space>
                        <Switch />
                        <Text>启用止损</Text>
                      </Space>
                    </Form.Item>
                  </Col>
                  <Col xs={24} md={12}>
                    <Form.Item label="默认止损比例 (%)" name="defaultStopLoss">
                      <InputNumber min={1} max={50} style={{ width: '100%' }} />
                    </Form.Item>
                  </Col>
                  <Col xs={24} md={12}>
                    <Form.Item name="riskWarningEnabled" valuePropName="checked">
                      <Space>
                        <Switch />
                        <Text>风险警告</Text>
                      </Space>
                    </Form.Item>
                  </Col>
                  <Col xs={24} md={12}>
                    <Form.Item name="confirmTransactions" valuePropName="checked">
                      <Space>
                        <Switch />
                        <Text>交易确认</Text>
                      </Space>
                    </Form.Item>
                  </Col>
                </Row>
              </Card>
              
              <Form.Item>
                <Button type="primary" htmlType="submit" loading={loading}>
                  保存交易设置
                </Button>
              </Form.Item>
            </Form>
              )
            },
            {
              key: 'data',
              label: <span><DatabaseOutlined />数据管理</span>,
              children: (
                 <div>
                   <Alert
                     message="数据管理"
                     description="管理您的数据，包括导入、导出和清理功能"
                     type="info"
                     showIcon
                     style={{ marginBottom: '24px' }}
                   />
                 
                   <List
              itemLayout="horizontal"
              dataSource={[
                {
                  title: '导出数据',
                  description: '导出所有投资组合和交易数据',
                  icon: <ExportOutlined />,
                  action: (
                    <Button type="primary" onClick={handleExportData}>
                      导出
                    </Button>
                  ),
                },
                {
                  title: '导入数据',
                  description: '从文件导入投资组合和交易数据',
                  icon: <ImportOutlined />,
                  action: (
                    <Button onClick={handleImportData}>
                      导入
                    </Button>
                  ),
                },
                {
                  title: '清除缓存',
                  description: '清除本地缓存数据以提高性能',
                  icon: <DeleteOutlined />,
                  action: (
                    <Button onClick={handleClearCache}>
                      清除
                    </Button>
                  ),
                },
                {
                  title: '重置设置',
                  description: '将所有设置重置为默认值',
                  icon: <ExclamationCircleOutlined />,
                  action: (
                    <Button danger onClick={handleResetSettings}>
                      重置
                    </Button>
                  ),
                },
              ]}
              renderItem={(item) => (
                <List.Item actions={[item.action]}>
                  <List.Item.Meta
                    avatar={item.icon}
                    title={item.title}
                    description={item.description}
                  />
                </List.Item>
              )}
                   />
                 </div>
               )
            }
          ]}
        />
      </Card>
    </div>
  );
};

export default Settings;